package com.matrix.index.ui.home.fragment

import android.annotation.SuppressLint
import android.view.LayoutInflater
import androidx.fragment.app.viewModels
import com.chad.library.adapter.base.BaseQuickAdapter
import com.matrix.basecore.arouter.ARouterUtils
import com.matrix.basecore.base.BaseFragment
import com.matrix.basecore.constant.Constant
import com.matrix.index.databinding.IndexBingFragmentBinding
import com.matrix.index.ui.home.adapter.RVBingAdapter
import com.matrix.index.ui.home.bean.BingImage
import com.matrix.index.ui.home.viewmodel.BingVM
import com.matrix.index.R
import com.matrix.index.net.IndexResult
import com.matrix.index.ui.home.bean.JuheJoke
import com.matrix.index.ui.home.bean.SearchBean
import org.litepal.LitePal

class IndexBingFragment : BaseFragment<IndexBingFragmentBinding>() {

    private val vm: BingVM by viewModels()
    private lateinit var adapter: RVBingAdapter
    private var bings: MutableList<BingImage.Images> = mutableListOf()

    override fun getViewBinding(): IndexBingFragmentBinding {
        return IndexBingFragmentBinding.inflate(layoutInflater)
    }

    override fun initView(inflater: LayoutInflater) {

        adapter = RVBingAdapter(R.layout.bing_item_layout, bings)
        mViewBinding.recyclerview.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {
//        vm.bingImage().observe(
//            this,
//            object : Observer<LiveData<List<BaseData>>>{
//
//            }
//        )
        vm.bingImage().observe(this) { value ->
            value.run {
                if (value.code == IndexResult.SUCCESS) {
                    bings.addAll((value.t as BingImage).images)
                    saveToDB(bings)
                    adapter.notifyDataSetChanged()
                    adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.ScaleIn);
                }
            }
        }
    }

    private fun saveToDB(bings: MutableList<BingImage.Images>) {
        for (item in bings) {
            var db = SearchBean(SearchBean.IMAGE)
            db.imageDesc = item.copyright + item.title
            db.imageUrl = Constant.BingBaseUrl + item.url
            db.timestamp = System.currentTimeMillis().toString()
            db.saveOrUpdate("imageUrl = ?", Constant.BingBaseUrl + item.url)
        }
    }

    override fun initListener() {
        adapter.setOnItemClickListener { _, _, position ->
            run {
                ARouterUtils.startPreviewActivityPath(transitionData(bings), position)
            }
        }
    }

    private fun transitionData(
        verticals: MutableList<BingImage.Images>,
    ): ArrayList<String> {
        var list: ArrayList<String> = arrayListOf()
        if (verticals.size > 0) {
            for (item in verticals) {
                list.add(Constant.BingBaseUrl + item.url)
            }
        }
        return list
    }
}